<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class Upload extends Controller
{
    // 上传图像
    public function upload(Request $request)
    {
        // 获取上传文件
        $file = $_FILES['img'];
        $domain_name = 'http://' . $_SERVER['HTTP_HOST']; //获取本地域名
        $filed_type = $request->input('filed_type') ? $request->input('filed_type') : 'other';
        if ($file['error']) return response('上传文件出错', 500);
        $name = $file['name'];
        $tmpName = $file['tmp_name'];
        $fileName = md5($name) . '-' . uniqid() . '.' . $name;
        $relativePath = 'uploads/' . $filed_type . '/';
        // 检测目录是否存在，不存在则自动创建
        if (!is_dir($relativePath))
            mkdir($relativePath, 0755, true);
        $bool = move_uploaded_file($tmpName, $relativePath . $fileName);
        $path = $domain_name . '/' . $relativePath . $fileName;
        if ($bool) {
            return response()->json(['path' => $path]);
        } else {
            return response('文件保存失败！', 500);
        }
    }
}